<script setup lang="ts">
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
import { showFailToast, showToast, showSuccessToast } from 'vant'
import 'vant/es/toast/style';
import { loginByPassword, sendMobileCode, loginByMobile } from '@/services/user'
import { useUserStore } from '@/stores';
// 表单实例
import type { FormInstance } from 'vant'
// import { onUnmounted } from 'vue';
const router = useRouter()
const route = useRoute()
const store = useUserStore()
// 是否同意协议
const agree = ref(false)
// 控制是睁眼还是闭眼
const show = ref(false)
// 登录的手机号码
const mobile = ref('13211112222')
// 登录的密码
const password = ref('abc12345')
// 短信验证码
const code = ref('')
// 假设默认是密码登录
const isPassword = ref(true)
// 登录
async function login() {
  if (!agree.value) return showFailToast('请勾选协议')
  // 验证完毕
  /*  if (isPassword.value) {
     // 账号和密码登录
     const { data } = await loginByPassword({ mobile: mobile.value, password: password.value })
     store.setUser(data)
   } else {
     // 手机验证码登录
     const { data } = await loginByMobile(mobile.value, code.value)
     store.setUser(data)
   } */

  const { data } = isPassword.value ? await loginByPassword({ mobile: mobile.value, password: password.value }) : await loginByMobile(mobile.value, code.value)
  store.setUser(data)
  showToast('登录成功')
  // 跳转到首页或者上一次退出时的页面
  const returnUrl = route.query.returnUrl as string
  router.push(returnUrl || '/user')
}


// 发送短信验证码
// 表单实例
const loginFormRef = ref<null | FormInstance>(null)
// 方式一：传统倒计时实现
// 倒计时数字初始值
// const time = ref(0)
// 定时器的标识id,因为这个数据不需要做响应式(不会在template模板中使用)
// let timeId: number
/* const send = async () => {
  // 1.如果短信倒计时正在进行中，不应该再次发送短信验证码
  if (time.value > 0) return
  // 2.输入的手机号码必须是正确的格式
  await loginFormRef.value!.validate('mobile')
  // 3.发送短信
  sendMobileCode(mobile.value, 'login').then(() => {
    showSuccessToast('发送短信成功')
    // 4.短信倒计时
    time.value = 60
    window.clearInterval(timeId)
    timeId = window.setInterval(() => {
      time.value--
      if (time.value <= 0) {
        window.clearInterval(timeId)
      }
    }, 1000)
  })
}
onUnmounted(() => {
  window.clearInterval(timeId)
}) */

// 方式二：使用@use/core库提供的方法来实现倒计时功能
/* import { useIntervalFn } from '@vueuse/core'
// 倒计时数字初始值
const time = ref(0)
// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否立即开启)
const { pause, resume } = useIntervalFn(() => {
  // 里面实现倒计时
  time.value--
  if (time.value <= 0) {
    pause()
  }
}, 1000)
onUnmounted(() => {
  pause()
})
const send = async () => {
  // 1.如果短信倒计时正在进行中，不应该再次发送短信验证码
  if (time.value > 0) return
  // 2.输入的手机号码必须是正确的格式
  await loginFormRef.value!.validate('mobile')
  // 3.发送短信
  sendMobileCode(mobile.value, 'login').then(() => {
    showSuccessToast('发送短信成功')
    // 4.开启短信倒计时
    time.value = 60
    resume()
  })
}
*/

// 方式三：导入封装好的倒计时函数
import { useInterVal } from '@/hooks/index'
const { time, start } = useInterVal()
const send = async () => {
  // 1.如果短信倒计时正在进行中，不应该再次发送短信验证码
  if (time.value > 0) return
  // 2.输入的手机号码必须是正确的格式
  await loginFormRef.value!.validate('mobile')
  // 3.发送短信
  sendMobileCode(mobile.value, 'login').then(() => {
    showSuccessToast('发送短信成功')
    // 4.开启短信倒计时
    start()
  })
}

// 为了让QQ登录成功后能拿到登录前的returnUrl地址，需要将该地址缓存起来
const setReturnUrl = (e: Event) => {
  e.preventDefault()
  // 保存用户
  store.setUrl(route.query.returnUrl as string)
  // 跳转到QQ登录页面
  // 回调地址
  const qq_callback = encodeURIComponent(import.meta.env.VITE_CALLBACK_URL)
  location.href = `https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=${qq_callback}`
}



</script>


<template>
  <cp-nav-bar right-text="注册" @click-right="router.push('/register')"></cp-nav-bar>
  <div class="login-page">
    <div class="login-head">
      <h3>{{ isPassword ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPassword = !isPassword">
        <span>{{ isPassword ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- form 表单 -->
    <van-form autocomplete="off" @submit="login" ref="loginFormRef">
      <van-field v-model="mobile" name="mobile" :rules="mobileRules" placeholder="请输入手机号" type="tel"></van-field>
      <!-- 密码登录 -->
      <van-field v-if="isPassword" v-model="password" :rules="passwordRules" placeholder="请输入密码"
        :type="show ? 'text' : 'password'">
        <template #button>
          <cp-icon @click="show = !show" :name="`login-eye-${show ? 'on' : 'off'}`"></cp-icon>
        </template>
      </van-field>
      <!-- 短信登录 -->
      <van-field v-else v-model="code" placeholder="短信验证码" :rules="codeRules">
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>

    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <a class="icon" @click="setReturnUrl">
        <img src="@/assets/qq.svg" alt="" />
      </a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url('./index.scss');
</style>


